package com.qianyitian.hope2.analyzer.config;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthorizeAspect {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("!execution(public * com.qianyitian.hope2.analyzer.controller.*.*(..))" +
            "&& execution(public * com.qianyitian.hope2.analyzer.controller.InfoController.*(..))")
    public void verify() {
    }

    @Before("verify()")
    public void doVerify() {
        logger.info("before verify");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 从 http 请求头中取出 token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        // 验证 token, 合法token
        boolean verifyToken = true;

        //根据token 在 redis 中获取用户信息 保存当前登录信息

        UserContext.setToken(token);
        UserContext.setUserId("1001");
        UserContext.setUserName("张一飞");
    }

    @After("verify()")
    public void doAfterVer() {
        UserContext.remove();
        logger.info("after verify");
    }

}